<?php

namespace app\common\logic;

use app\common\helper\AliOss;
use app\common\helper\SendSmsHelper;
use app\common\model\Admin;
use app\common\model\AiImage;
use app\common\model\AiOrder;
use app\common\model\SignLog;
use app\common\model\User;
use think\Exception;
use think\exception\ValidateException;
use think\helper\Str;

class UserLogic extends BaseLogic
{
    public static function findOrCreateUser($openid,$data)
    {
        $config = cache('config');
        if (!$openid) throwError("openid不能空");
        $token = md5($openid . time());
        $user = User::where('openid',$openid)
            ->field('nick,avatar,money,id,xianqi,qwen_token,status')
            ->find();
        if (!$user) {
            $temp = [
                "openid" => $openid,
                "avatar" => $config['wx_avatar'],
                "nick" => getRandNick(),
                "xianqi" => $config['reg_xianqi'],
                "qwen_token" => 10000,
                "status" => 1
            ];
            if (!empty($data['share_id'])) {
                $temp['pid'] = $data['share_id'];
                $user = User::create($temp);
            } else {
                $user = User::create($temp);
            }
        }
        $user->token = $token;
        $user->save();
        return $user;
    }

    public static function updateUserInfo($data)
    {
        $uid = $data['user_id'];
        unset($data['user_id']);
        $user = User::where('id',$uid)->find();
        $user->save($data);
    }

    // 扩容仓库
    public static function addStore($user)
    {
        if ($user->xianqi < 100 ) throwError('仙气不足');
        $user->xianqi -= 100;
        $user->store_num += 5;
        $user->save();
    }

    public static function getImageList($data)
    {
        return AiImage::where("user_id",$data['user_id'])
            ->order('id desc')
            ->field('store_type,path,prompt,store,id')
            ->where('store_type',$data['type'])
            ->paginate(["list_rows"=>$data['limit'],"page"=>$data['page']]);
    }

    public static function changeStore($data,$user)
    {
        $count = AiImage::where("user_id",$data['user_id'])
            ->where('store_type',$data['type'])
            ->count();
        if ($count >= $user->store_num) throwError('空间不足');
        $image = AiImage::where("id",$data['id'])
            ->where('user_id',$data['user_id'])
            ->find();
        if ($image) {
            $image->store_type = $data['type'];
            $image->save();
        }
    }

    public static function delImage($data)
    {
        $image = AiImage::where("id",$data['id'])
            ->where('user_id',$data['user_id'])
            ->find();
        if ($image) {
            (new AliOss())->del([ltrim($image->path, '/')]);
            delFile($image->path);
            $image->delete();
        }
    }

    public static function getUserInfo($uid)
    {
        $info = User::where("id",$uid)
            ->field("id,avatar,nick,token,xianqi,is_ping,store_num,qwen_token")
            ->find();
        return $info;
    }

    public static function register($data)
    {
        try {
            if (!(new SendSmsHelper())->checkYzm($data['tel'],'register',$data['code'])) {
                throwError('验证码错误');
            }
            $data['password'] = password_hash($data['password'],PASSWORD_DEFAULT);
            return User::create($data);
        } catch (ValidateException | Exception $exception) {
            throwError($exception->getMessage());
        }
    }

    public static function forget($data)
    {
        try {
            if (!(new SendSmsHelper())->checkYzm(['tel'=>$data['tel'],'code'=>$data['code'],'type'=>'forget'])) {
                throwError('验证码错误');
            }
            $data['password'] = password_hash($data['password'],PASSWORD_DEFAULT);
            return User::update(['password'=>$data['password']],['tel'=>$data['tel']]);
        } catch (ValidateException | Exception $exception) {
            throwError($exception->getMessage());
        }
    }

    public static function login($data)
    {
        try {
            $user = Admin::where('user_name',$data['username'])
                ->field('id,user_name,real_name,token,auth_group_id,pass_word')
                ->find();
            if (!$user) throwError('用户名密码错误');
            $token = md5(time() . Str::random());
            if ($data['login_type'] == "password") {
                if (!password_verify($data['password'],$user->pass_word)) throwError('用户名密码错误');
            } else {
                if (!(new SendSmsHelper())->checkYzm($data['login_tel'],'login',$data['login_code'])) {
                    throwError('手机验证码错误');
                }
            }
            $user->token = $token;
            $user->save();
            session("user",$user);
            return $user;
        } catch (ValidateException | Exception $exception) {
            throwError($exception->getMessage());
        }
    }

    // 评价加仙气
    public static function setPing($uid)
    {
        $user = User::where("id",$uid)->find();
        if ($user && $user->is_ping !== 1) {
            $qi = cache('config')['xianqi'];
            $user->is_ping = 1;
            $user->xianqi += $qi;
            $user->save();
        }
    }
    // 分享加仙气
    public static function setSign($uid,$type) {
        $config = cache('config');
        $user = User::where("id",$uid)->find();
        $exit = SignLog::where('user_id',$uid)
            ->whereDay('create_time')
            ->find();
        if (!$exit) {
            $user->xianqi+= $config[$type . "_xianqi"];
            if ($type == 'sign') {
                $user->sign_all ++;
                $sign = SignLog::where("user_id",$uid)
                    ->whereDay('create_time','yesterday')
                    ->where('sign',1)
                    ->find();
                if ($sign) {
                    $user->sign_day ++;
                } else {
                    $user->sign_day = 1;
                }
            }
            $user->save();
            SignLog::create([
                "user_id" => $uid,
                $type => 1,
                "create_time" => time()
            ]);
        } else {
            if ($exit->$type != 1) {
                $user->xianqi += $config[$type . "_xianqi"];
                if ($type == 'sign') {
                    $user->sign_all ++;
                    $sign = SignLog::where("user_id",$uid)
                        ->whereDay('create_time','yesterday')
                        ->where('sign',1)
                        ->find();
                    if ($sign) {
                        $user->sign_day ++;
                    } else {
                        $user->sign_day = 1;
                    }
                }
                $user->save();
                $exit->save([$type => 1]);
            }
        }
    }

    public static function getSign($uid)
    {
        $exit = SignLog::where('user_id',$uid)
            ->whereDay('create_time')
            ->find();
        if (!$exit) {
            $exit = [
                "share" => -1,
                "create" => -1,
                "sign" => -1
            ];
        }
        // 是否正在创作的订单
        $createIng = AiOrder::where("user_id",$uid)
            ->whereIn('task_status',["PENDING","RUNNING"])
            ->find();
        $temp_count = AiImage::where("user_id",$uid)
            ->where('store_type','temp')->count();
        $private_count = AiImage::where("user_id",$uid)
            ->where('store_type','private')->count();
        $public_count = AiImage::where("user_id",$uid)
            ->where('store_type','public')->count();
        $exit['create_ing'] = $createIng ? 1 : -1;
        $exit['temp_count'] = $temp_count;
        $exit['public_count'] = $public_count;
        $exit['private_count'] = $private_count;
        return $exit;
    }

}